<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">院校名称：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入院校名称" v-model="listQuery.academyName" clearable></el-input>
      <span style="margin-left:10px">所属城市：</span>
      <el-cascader @keyup.enter.native="handleFilter" change-on-select clearable placeholder="全部" expand-trigger="click" :options="areaCascadeOptionss" v-model="listQuery.areaId"></el-cascader>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item addAcademy"  type="success" icon="el-icon-plus" @click="addAcademy">创建院校</el-button>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row style="width: 100%">
      <el-table-column v-if='showAllDel' type="selection" width="55" />
      <el-table-column min-width="100" align="center" label="院校 ID" >
      <template slot-scope="scope">
          <span v-if="scope.row.id != null">{{scope.row.id}}</span>
          <span v-else>{{scope.row.academyId}}</span>
      </template>
      </el-table-column>
      <el-table-column min-width="220" align="center" label="院校名称" prop="academyName" />  
      <el-table-column min-width="100" align="center" label="院校性质" prop="academyAttr" />
      <el-table-column min-width="100" align="center" label="院校类型" prop="academyLevel" />
      <el-table-column min-width="100" align="center" label="所属地区" >
        <template slot-scope="scope">
           <span v-if="scope.row.province==scope.row.city">{{scope.row.province}}</span>
           <span v-else>{{scope.row.province}}-{{scope.row.city}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150" align="center" label="院校网站" prop="website" />
      <el-table-column min-width="150" align="center" label="院校电话" prop="telephone" />
      <el-table-column min-width="150" align="center" label="是否前台展示">
        <template slot-scope="scope">
          <span v-if="scope.row.show == 1">是</span>
          <span v-else>否</span>
      </template>
      </el-table-column>
      <el-table-column align="center" label="是否展示在前台/编辑" min-width="150">
        <template slot-scope="{row}">
          <el-button size="small" type="primary" @click="handleToggleAllowSpeak(row)">{{ row.show | transAudit(false)}}</el-button>
          <el-button size="small" @click="handleModifyStatus(row)" type="primary">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 编辑窗口表单 -->
    <el-dialog title="编辑院校资料" :visible.sync="dialogFormVisible" center v-if="dialogFormVisible" class="dialogWtgth" :before-close="handleClose">
        <el-form :model="temp" :rules="rules" ref="ruleForm" class="form">
          <el-form-item label="院校名称" label-width="80px" prop="academyName">
            <el-input v-model="temp.academyName"></el-input>
          </el-form-item>
          <el-form-item label="校标/背景" label-width="80px">
            <el-col :span="12">
            <el-upload
              style="margin-left:10px"
              :headers="headers"
              action="/tools/oss/upload"
              :on-preview="handlePreview"
              :before-remove="beforeRemove_icon"
              :on-remove="handleRemove_icon"
              :on-success="handleUploadSuccess_icon"
              list-type="picture"
              accept=".png,.jpg,.jpeg,.gif"
              :file-list="fileList_icon"
              :limit="2">
              <el-button size="small" type="primary">上传校标</el-button> <span>（建议上传尺寸 200 * 200）</span>
            </el-upload>
            </el-col>
            <el-col :span="12">
            <el-upload
              style="margin-left:10px"
              :headers="headers"
              action="/tools/oss/upload"
              :on-preview="handlePreview"
              :before-remove="beforeRemove_image"
              :on-remove="handleRemove_image"
              :on-success="handleUploadSuccess_image"
              list-type="picture"
              accept=".png,.jpg,.jpeg,.gif"
              :file-list="fileList_image"
              :limit="2">
              <el-button size="small" type="primary">上传背景</el-button><span>（建议上传尺寸 750 * 380）</span>
            </el-upload>
            </el-col>            
          </el-form-item>
          <el-form-item label="院校性质" label-width="80px" prop="academyAttr">
            <el-input v-model="temp.academyAttr"></el-input>
          </el-form-item>
          <el-form-item label="院校类型" label-width="80px" prop="academyLevel">
            <el-input v-model="temp.academyLevel"></el-input>
          </el-form-item>
          <el-form-item label="院校特色" label-width="80px" prop="feature">
            <el-input v-model="temp.feature"></el-input>
          </el-form-item>
          <el-form-item label="院校地址" label-width="80px" prop="address">
            <el-input v-model="temp.address"></el-input>
          </el-form-item>
          <el-form-item label="院校网站" label-width="80px" prop="website">
            <el-input v-model="temp.website"></el-input>
          </el-form-item>
          <el-form-item label="院校电话" label-width="80px" prop="telephone">
            <el-input v-model="temp.telephone"></el-input>
          </el-form-item>
          <el-form-item label="所属省市" label-width="80px" :rules="[{required: true}]">
            <el-cascader change-on-select  clearable placeholder="请选择所属省市" expand-trigger="click" :options="areaCascadeOptionss" v-model="areaOption" />
            <span class="hint">&nbsp;&nbsp;&nbsp;学校所属省市必须选择到 市级</span>
          </el-form-item>
          <el-form-item label="院校介绍" label-width="80px" prop="introduction">
            <Tinymce :height=400 ref="editor" v-model="temp.introduction"/>
          </el-form-item>
          <el-form-item label="招生简章" label-width="80px" prop="catalog">
            <Tinymce :height=400 ref="editor" v-model="temp.catalog"/>
          </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogFormVisible = false" type="info" plain >取 消</el-button> -->
        <el-button @click="handleClose" type="info" plain >取 消</el-button>
        <el-button type="primary" @click="updateForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { getList, getNameList, getId_audit, update, modification, getId, getArea, getAreaCascadeSupply, isShow } from '@/api/academy'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'

const transAudit = (show, boolean = true) => {
  if (boolean) return show == 0 ? '取消展示' : '前台展示'
  return show == 0 ? '前台展示' : '取消展示'
}
export default {
  name: 'list',
  components: { Tinymce },
  data() {
    return {
      headers:{},
      list: null,
      total: null,
      listLoading: true,
      tableKey: 0,
      showAllDel: false,
      areaCascadeOptionss:[],
      areaOption:[],
      fileList_icon:[],
      fileList_image:[],
      areaOptionString:[],
      listQuery: {
        academyLevel: '',
        academyName: '',
        city: '',
        cover: '',
        feature: '',
        show:null,
        id: null,
        pageNo: 1,
        pageSize: 10,
        province: '',
        areaId:[],
        areaLabels: ''
      },
      temp: {
        labels: [],
        areaId:[],
        areaLabels: null
      },
      dialogFormVisible: false,
      rules: {
        academyName:  [{ required: true, message: '请输入院校名称', trigger: 'change' }],
        telephone:  [{ required: true, message: '请输入院校电话', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getList()
    this.getAreaCascadeSupply()
    this.headers = { accessToken:getToken() }
  },
  filters: {
    transAudit
  },
  methods: {
    handleClose() {
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
      }).catch(() => {})
    },
    // 是否展示在前台
    handleToggleAllowSpeak({ show, id, academyId }) {
      isShow({
        show: show == 1 ? 0 : 1,
        id : id || academyId
      })
        .then(() => {
          this.$message({
            message: `${transAudit(show, false)}成功！`,
            type: 'success'
          })
          this.getNameList()
        }).catch(err => {})
    },
    // 获得完整的区域级联,但是要删除 区/县/镇
    getAreaCascadeSupply(){
      getAreaCascadeSupply().then(res => {
        if(res.code == 0){
          res.data.forEach(item => {
            if(item.children){
              item.children.forEach(i => {
                delete i.children
              })
            }
          })
          this.areaCascadeOptionss = res.data
        }
      }).catch(err => {})
    },
    // 映射 Actions
    ...mapActions(['GetAreaCascadeOptions']),
    // 获取分页列表
    getList() {
      this.listLoading = true
      const params = this.listQuery
      getList(params).then(response => {
        const { code, data: { total, list = [] } } = response
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      }).catch(err => {
        this.listLoading = false
      })
    },
    //上传校标/背景
    handleUploadSuccess_icon(rst, file, fileList_icon){
      const { code, data:{ picUrlList } } = rst
      if(code == 0){
        this.temp['icon'] = picUrlList[0]
        this.fileList_icon = [{ name: file.url, url: file.url }]
      }
    },
    handleUploadSuccess_image(rst, file, fileList_image){
      const { code, data:{ picUrlList } } = rst
      if(code == 0){
        this.temp.image = picUrlList[0]
        this.fileList_image = [{ name: file.url, url: file.url }]
      }
    },
    handlePreview(file) {
    },
    beforeRemove_icon(file, fileList) {
      return this.$confirm(`如校标已存在,只能更换不能为空,否则删除后保存无效,是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    handleRemove_icon(file, fileList_icon){
      this.temp.icon = ''
    },
    beforeRemove_image(file, fileList) {
      return this.$confirm(`如背景已存在,只能更换不能为空,否则删除后保存无效,是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    handleRemove_image(file, fileList_image) {
      this.temp.image = ''
    },
    // 通过院校名称和地区模糊查询
    getNameList(){
      this.listLoading = true
      // 通过三级联选择器得到的地址id调接口获得地区详情
      const id = { id: this.listQuery.areaId[this.listQuery.areaId.length - 1] }
      if(this.listQuery.academyName == '' && id.id == null){
        this.getList()
        return
      }else if(this.listQuery.academyName != '' && id.id == null){
        const params = {
          academyName: this.listQuery.academyName,
          province: '',
          city : '',
          pageNo: this.listQuery.pageNo,
          pageSize: this.listQuery.pageSize
        }
        getNameList(params).then(res => {
          if(res.code == 0){
            this.list = res.data.list
            this.total = res.data.total
            this.listQuery.pageSize = res.data.pageSize
            this.listLoading = false
          }
        }).catch(err => {})
      } else if(id.id != null){
        getArea(id).then(res => {
          if(res.code == 0){
            if(res.data.fatherLabel){
              this.listQuery.province = res.data.fatherLabel
              this.listQuery.city = res.data.label
            }else{
              this.listQuery.province = res.data.label
              this.listQuery.city = ''
            }
            const params = {
              academyName: this.listQuery.academyName,
              province: this.listQuery.province,
              city: this.listQuery.city,
              pageNo: this.listQuery.pageNo,
              pageSize: this.listQuery.pageSize
            }
            getNameList(params).then(res => {
              if(res.code == 0){
                this.list = res.data.list
                this.total = res.data.total
                this.listQuery.pageSize = res.data.pageSize
                this.listLoading = false
              }
            }).catch(err => {})
          }
        }).catch(err => {})
      }
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.listQuery.pageSize = 10
      this.getNameList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getNameList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getNameList()
    },
    // 根据id查询学校信息
    handleModifyStatus(row) {
      if(row.id){
        getId(row.id).then(res => {
          if(res.code == 0){
            this.areaOption = []
            this.areaOptionString = []
            this.temp = res.data[0]
            if(this.temp.icon){
              this.fileList_icon = [{ name:this.temp.icon, url:this.temp.icon }]
            }else{
              this.fileList_icon = []
            }
            if(this.temp.image){
              this.fileList_image = [{ name:this.temp.image, url:this.temp.image }]
            }else{
              this.fileList_image = []
            }
            this.temp['id'] = row.id
            this.dialogFormVisible = true
            this.areaCascadeOptionss.forEach(item => {
              if(item.label == this.temp.province){
                this.areaOption.push(item.value)
              }
            })
            this.areaCascadeOptionss.forEach(item => {
              item.children.forEach(i => {
                if(i.label == this.temp.city){
                  this.areaOption.push(i.value)
                }
              })
            })
          }
        }).catch(err => {})
      }else {
        getId(row.academyId).then(res => {
          if(res.code == 0){
            this.areaOption = []
            this.areaOptionString = []
            this.temp = res.data[0]
            if(this.temp.icon){
              this.fileList_icon = [{ name:this.temp.icon, url:this.temp.icon }]
            }else{
              this.fileList_icon = []
            }
            if(this.temp.image){
              this.fileList_image = [{ name:this.temp.image, url:this.temp.image }]
            }else{
              this.fileList_image = []
            }
            this.temp['id'] = row.academyId
            this.dialogFormVisible = true
            this.areaCascadeOptionss.forEach(item => {
              if(item.label == this.temp.province){
                this.areaOption.push(item.value)
              }
            })
            this.areaCascadeOptionss.forEach(item => {
              item.children.forEach(i => {
                if(i.label == this.temp.city){
                  this.areaOption.push(i.value)
                }
              })
            })
          }
        }).catch(err => {})
      }
    },
    getInnerText(str){
      let description = str
      description = description.replace(/(\n)/g, '')
      description = description.replace(/(\t)/g, '')
      description = description.replace(/(\r)/g, '')
      description = description.replace(/<\/?[^>]*>/g, '')
      description = description.replace(/\s*/g, '')
      return description.length
    },
    // 保存院校信息
    updateForm() {
      console.log('this.temp', this.temp)
      var lengs = 0
      if(this.temp.catalog){
        const strs = this.temp.catalog
        lengs = this.getInnerText(strs)
        // if(lengs==0){
        //   this.temp.catalog = ""
        // }
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if(this.temp.academyName.trim().length == 0 || this.temp.telephone.length == 0){
            this.$message({
              title: '失败',
              message: '带 * 号项为必填项，请输入后再保存',
              type: 'error',
              duration: 2000
            })
            return
          }
          // 通过地域id得到省市字符串
          if(this.areaOption.length != 2){
            this.$message({
              title: '失败',
              message: '学校所属省市必须选择到 市级',
              type: 'error',
              duration: 2000
            })
            return
          }
          const id = { id: this.areaOption[this.areaOption.length - 1] }
          const { temp } = this
          getArea(id).then(res => {
            if(res.code == 0){
              if(res.data.fatherLabel){
                temp.province = res.data.fatherLabel
                temp.city = res.data.label
              }else{
                temp.province = res.data.label
                temp.city = ''
              }
            }
            const params = {}
            params['academyName'] = temp['academyName']
            params['academyId'] = temp['id']
            params['academyAttr'] = temp['academyAttr']
            params['academyLevel'] = temp['academyLevel']
            params['feature'] = temp['feature']
            params['address'] = temp['address']
            params['website'] = temp['website']
            params['telephone'] = temp['telephone']
            params['province'] = temp.province
            params['city'] = temp.city
            params['introduction'] = temp['introduction']
            if(lengs > 0){
              params['catalog'] = temp['catalog']
            }

            params['icon'] = temp.icon
            params['image'] = temp.image

            modification(params).then(response => {
              const { code, message } = response
              if (code == 0) {
                this.getNameList()
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              }else{
                this.$message({
                  title: '失败',
                  message: message,
                  type: 'error',
                  duration: 2000
                })
              }
            }).catch(err => {
            })
          }).catch(err => {})
        }
      })
    },
    // 新增院校
    addAcademy(){
      this.$router.push({ path:'./add' })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx {
  width: 160px;
  height: 80px;
  overflow: hidden;
  margin: 0 auto;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.form{
  width: 90%;
}
.hint{
  font-size: 12px;
  color: #999999;
}
.addAcademy{
  margin-right: 50px;
  float: right;
}
</style>